package com.ghsc.yigou.live.ui.activity

import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.os.Bundle
import android.text.TextUtils
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alivc.auicommon.common.base.util.Utils
import com.alivc.auicommon.common.biz.exposable.enums.LiveStatus
import com.alivc.auicommon.common.roombase.Const
import com.alivc.auicommon.core.base.Actions
import com.alivc.auicommon.core.event.EventManager
import com.alivc.auimessage.MessageService
import com.alivc.auimessage.MessageServiceFactory
import com.alivc.auimessage.listener.InteractionCallback
import com.alivc.auimessage.model.base.InteractionError
import com.alivc.auimessage.model.lwp.GetGroupInfoRequest
import com.alivc.auimessage.model.lwp.GetGroupInfoResponse
import com.alivc.auimessage.model.lwp.JoinGroupRequest
import com.alivc.auimessage.model.lwp.JoinGroupResponse
import com.aliyun.aliinteraction.player.LivePlayerService
import com.aliyun.aliinteraction.player.LivePlayerServiceImpl
import com.aliyun.aliinteraction.roompaas.message.AUIMessageService
import com.aliyun.aliinteraction.roompaas.message.AUIMessageServiceFactory
import com.aliyun.aliinteraction.uikit.core.ComponentManager
import com.aliyun.aliinteraction.uikit.core.LiveConst
import com.aliyun.aliinteraction.uikit.uibase.util.DialogUtil
import com.aliyun.auiappserver.model.LiveModel
import com.aliyun.auipusher.AnchorPreviewHolder
import com.aliyun.auipusher.LiveContext
import com.aliyun.auipusher.LiveParam
import com.aliyun.auipusher.LiveRole
import com.aliyun.auipusher.LiveService
import com.aliyun.auipusher.LiveServiceImpl
import com.aliyun.auipusher.manager.LiveLinkMicPushManager
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.event.SchedulerTransformer
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.showToast
import com.cn.appcore.utils.GsonUtil
import com.ghsc.yigou.live.R
import com.ghsc.yigou.live.config.CustSignKey
import com.ghsc.yigou.live.databinding.ActivityLiveBinding

/**
 * 项目：YiGouLive
 * 包名：com.ghsc.yigou.live.ui.activity
 * 类名：LiveBroadcastActivity
 * 创建时间：2024/8/1 10:59
 * 创建人 @author： xiaolin
 * 描述 ：Todo...
 */
class LiveBroadcastActivity  : BaseVMActivity<LiveViewModel, ActivityLiveBinding>(){
    override fun attachLayoutRes(): Int {
        return R.layout.activity_live
    }

    override fun attachVMClass(): Class<LiveViewModel>? {
        return LiveViewModel::class.java
    }


    var bundle : Bundle? =null
    var   pageParam: LiveParam? =null

    private var role: LiveRole? = null
    private var liveStatus: LiveStatus? = null
    private var liveId: String? = null
    private var liveModel: LiveModel? = null
    private var userNick: String? = null
    private var userExtension: String? = null
    private var groupId: String? = null
    private var tips: String? = null
    private var userAvatar: String? = null


    //消息服务  弹幕  开始直播 结束直播 更新 申请连麦 等
    private var auiMessageService: AUIMessageService? = null
    //交互
//    private var interactionService: InteractionService? = null

    //媒体推流服务
    private var pushManager: LiveLinkMicPushManager? = null
    //页面状态
    private var liveContext: LiveContext? = null


    //直播详情
    private var liveService: LiveService? = null
    //直播播放服务 播放 暂停 等
    private var livePlayerService: LivePlayerService? = null
    private val componentManager = ComponentManager()
    private val anchorPreviewHolder = AnchorPreviewHolder()

    private var messageService: MessageService? = null

    private var isPushing = false
    private var isFollow=false


    private val mHeadAdapter: LiveHeadListAdapter by lazy { LiveHeadListAdapter() }
    var mListHead = arrayListOf<String>()


    override fun initView() {
        bundle = intent.extras
        pageParam = intent.getSerializableExtra(LiveConst.PARAM_KEY_LIVE_PARAM) as LiveParam?
        pageParam?.let {
            liveId = it.liveId
            liveModel = it.liveModel
            role = it.role
            liveStatus = LiveStatus.of(liveModel!!.status)
            userNick = it.userNick
            userAvatar = it.userAvatar
            userExtension = it.userExtension
            tips = pageParam!!.notice
            groupId = liveModel!!.chatId
            loge("liveModel=" + liveModel)
        }
        // 获取RoomChannel
        messageService = MessageServiceFactory.getMessageService()
        if (!messageService!!.isLogin) {
            showToast("未登录")
            finish()
            return
        }

        pushManager = LiveLinkMicPushManager(this, null)

        liveContext = LiveContextImpl()
        val decorView = window.decorView
        componentManager.scanComponent(decorView)
        componentManager.dispatchInit(liveContext!!)
        joinGroup()


        rxBusSubscription = RxBus.getDefault().toObservable(RxBusBean::class.java)
            .compose(SchedulerTransformer())
            .subscribe { rxBusBean ->
                when {
                    rxBusBean.id == CustSignKey.CUST_LIVE_CART && rxBusBean.sign == CustSignKey.CUST_LIVE_CART -> {
                        //todo  直播间 购物
                        var isOwner= rxBusBean.anyBean as Boolean
                        if(isOwner){
                            showToast("暂未开放")
                        }
                    }
                    rxBusBean.id == CustSignKey.CUST_LIVE_SHARE_URL && rxBusBean.sign == CustSignKey.CUST_LIVE_SHARE_URL -> {
                        //todo  直播间 分享
                        var url=rxBusBean.anyBean as String
                        loge("分享链接="+url)
                        showToast("暂未开放")
                    }
                }
            }


        binding.rvListHead.layoutManager =  LinearLayoutManager(this, RecyclerView.HORIZONTAL,false)
        binding.rvListHead.adapter = mHeadAdapter
        mHeadAdapter.setNewInstance(mListHead)
        mHeadAdapter.setOnItemClickListener { adapter, view, position ->
            //某个用户信息

        }
        getImListData()

    }
    /** 当前观众 list **/
    private fun getImListData(){
//        val req = ImListGroupUserReq()
//        req.groupId = groupId
//        req.sortType = SortType.TIME_ASC.value
//        req.pageNum = 1
//        req.pageSize = 50
//        interactionService!!.listGroupUser(req, object : Callback<ImListGroupUserRsp> {
//            override fun onSuccess(rsp: ImListGroupUserRsp) {
//                val total = rsp.total
//                val userList = rsp.userList
//                loge("还有数据="+total+"groupId="+groupId)
//                var mListIds: MutableList<String> = ArrayList()
//                mListIds.clear()
//                if (userList.size>0){
//                    for (i in userList.indices)
//                        mListIds.add(userList[i].userId)
//                    val map: HashMap<String, Any> = HashMap()
//                    map["uids"] = StringUtil.convertListToString(mListIds)!!
//                    map["vid"] =liveId!!
//                    var json= GsonUtil.mapToJsonStrObjEncryption(map)
//                    mViewModel.onGetIdsListMethod(json!!)
//                }
//
//            }
//
//            override fun onError(error: Error) {}
//        })
    }

    private fun isActivityValid(): Boolean {
        return !isFinishing && !isDestroyed
    }
    private fun onEnterRoomError(errorMsg: String) {
        componentManager.dispatchEnterRoomError(errorMsg)
    }
    private fun onEnterRoomSuccess(liveModel: LiveModel) {
        this.liveModel = liveModel
        componentManager.dispatchEnterRoomSuccess(liveModel)
        val request = GetGroupInfoRequest()
        request.groupId = groupId
        auiMessageService!!.messageService.getGroupInfo(
            request,
            object : InteractionCallback<GetGroupInfoResponse?> {
                override fun onSuccess(response: GetGroupInfoResponse?) {
                    if (Utils.isActivityValid(this@LiveBroadcastActivity)) {
                        componentManager.post(Actions.GET_GROUP_STATISTICS_SUCCESS, response)
                    }
                }

                override fun onError(error: InteractionError) {}
            })
    }
    private fun joinGroup() {
        val request = JoinGroupRequest()
        request.groupId = groupId
        messageService!!.joinGroup(request, object : InteractionCallback<JoinGroupResponse?> {
            override fun onSuccess(data: JoinGroupResponse?) {
                if (isActivityValid()) {
                    onEnterRoomSuccess(liveModel!!)
                }
            }

            override fun onError(error: InteractionError) {
                if (isActivityValid()) {
                    onEnterRoomError(error.msg)
                    // 进入失败时, 退出房间
                    val message = String.format("进入房间失败：\n%s", error.msg)
                    DialogUtil.confirm(this@LiveBroadcastActivity, message,
                        { finish() }
                    ) { finish() }
                }
            }
        })
    }

    /**
     * 当系统的配置信息发生改变时，系统会调用此方法。注意，只有在配置文件AndroidManifest中处理了configChanges属性对应的设备配置，该方法才会被调用。
     * 如果发生设备配置与在配置文件中设置的不一致，则Activity会被销毁并使用新的配置重建。
     * 例如：当屏幕方向发生改变时，Activity会被销毁重建，如果在AndroidManifest文件中处理屏幕方向配置信息如下
     */
    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        componentManager.dispatchActivityConfigurationChanged(newConfig)
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        componentManager.dispatchActivityResult(requestCode, resultCode, data)
    }
    override fun onPause() {
        super.onPause()
        componentManager.dispatchActivityPause()
    }

    override fun onResume() {
        super.onResume()
        componentManager.dispatchActivityResume()
    }

    override fun onBackPressed() {
        if (!componentManager.interceptBackKey()) {
            super.onBackPressed()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        componentManager.dispatchActivityDestroy()
        liveContext!!.messageService.removeAllMessageListeners()
    }

    override fun finish() {
        super.finish()
        componentManager.dispatchActivityFinish()
    }
    inner class LiveContextImpl : LiveContext {
        override fun getActivity(): Activity {
            return this@LiveBroadcastActivity
        }

        override fun getRole(): LiveRole {
            return this@LiveBroadcastActivity.role!!
        }

        override fun getNick(): String {
            return this@LiveBroadcastActivity.userNick!!
        }
        override fun getAvatar(): String {
            return this@LiveBroadcastActivity.userAvatar!!
        }
        override fun getTips(): String {
            return this@LiveBroadcastActivity.tips!!
        }

        override fun getLiveStatus(): LiveStatus {
            return this@LiveBroadcastActivity.liveStatus!!
        }

        override fun getEventManager(): EventManager {
            return this@LiveBroadcastActivity.componentManager
        }

        override fun isPushing(): Boolean {
            return this@LiveBroadcastActivity.isPushing
        }

        override fun setPushing(isPushing: Boolean) {
            this@LiveBroadcastActivity.isPushing = isPushing
        }
        override fun isFollow(): Boolean {
            return this@LiveBroadcastActivity.isFollow
        }
        override fun isLandscape(): Boolean {
            return this@LiveBroadcastActivity.resources
                .configuration.orientation == Configuration.ORIENTATION_LANDSCAPE
        }

        override fun setLandscape(landscape: Boolean) {
            if (landscape) {
                // 竖屏 => 横屏
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
            } else {
                // 横屏 => 竖屏
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
            }
        }

        override fun getLiveId(): String {
            return this@LiveBroadcastActivity.liveId!!
        }

        override fun getGroupId(): String {
            return this@LiveBroadcastActivity.groupId!!
        }

        override fun getUserId(): String {
            return Const.getUserId()
        }

        override fun getLiveService(): LiveService {
            if (this@LiveBroadcastActivity.liveService == null) {
                this@LiveBroadcastActivity.liveService = LiveServiceImpl(this@LiveBroadcastActivity, liveContext)
            }
            return this@LiveBroadcastActivity.liveService!!
        }

        override fun getLivePlayerService(): LivePlayerService {
            if (this@LiveBroadcastActivity.livePlayerService == null) {
                this@LiveBroadcastActivity.livePlayerService = LivePlayerServiceImpl(this@LiveBroadcastActivity)
            }
            return this@LiveBroadcastActivity.livePlayerService!!
        }

        override fun getMessageService(): AUIMessageService {
            if (this@LiveBroadcastActivity.auiMessageService == null) {
                this@LiveBroadcastActivity.auiMessageService = AUIMessageServiceFactory.getMessageService(groupId)
            }
            return this@LiveBroadcastActivity.auiMessageService!!
        }

        override fun getLiveLinkMicPushManager(): LiveLinkMicPushManager {
            return this@LiveBroadcastActivity.pushManager!!
        }

        override fun getLiveModel(): LiveModel {
            return this@LiveBroadcastActivity.liveModel!!
        }

        override fun getAnchorPreviewHolder(): AnchorPreviewHolder {
            return this@LiveBroadcastActivity.anchorPreviewHolder
        }

        override fun isOwner(userId: String): Boolean {
            if (liveModel != null) {
                val anchorId = liveModel.anchorId
                if (!TextUtils.isEmpty(anchorId)) {
                    return TextUtils.equals(anchorId, userId)
                }
            }
            return false
        }
    }
}